package main

import (
	"fmt"
	"log"

	"mysql-parser/sqlparser"
)

func main() {
	fmt.Println("=== MySQL Parser 子查询示例演示 ===")
	fmt.Println("基于实际测试验证的子查询支持能力")
	fmt.Println()

	// 创建解析器实例
	parser, err := sqlparser.New(sqlparser.Options{
		MySQLServerVersion: "5.7.0",
	})
	if err != nil {
		log.Fatal(err)
	}

	// WHERE子查询示例 - 完全支持
	fmt.Println("=== ✅ WHERE子查询示例（完全支持）===")
	whereSubqueries := []string{
		"SELECT * FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 100)",
		"SELECT * FROM products WHERE price > (SELECT AVG(price) FROM products)",
		"SELECT * FROM users WHERE EXISTS (SELECT 1 FROM orders WHERE orders.user_id = users.id)",
		"SELECT * FROM products WHERE category_id = (SELECT id FROM categories WHERE name = 'Electronics')",
		"SELECT name FROM users WHERE id IN (SELECT DISTINCT user_id FROM orders)", // 简单IN子查询
	}

	for i, sql := range whereSubqueries {
		fmt.Printf("WHERE子查询示例 %d: %s\n", i+1, sql)
		
		stmt, err := parser.Parse(sql)
		if err != nil {
			log.Printf("解析错误: %v", err)
			continue
		}

		// 提取所有表名
		tables := sqlparser.ExtractAllTables(stmt)
		fmt.Printf("  涉及的表: %v\n", tables)

		// 表分析
		tableAnalysis := sqlparser.AnalyzeTables(stmt)
		fmt.Printf("  表分析: 表数量=%d, 有连接=%v, 有子查询=%v\n",
			tableAnalysis.TableCount, tableAnalysis.HasJoins, tableAnalysis.HasSubquery)

		// 聚合分析
		aggAnalysis := sqlparser.AnalyzeAggregation(stmt)
		fmt.Printf("  聚合分析: 包含聚合=%v, 聚合函数=%v\n",
			aggAnalysis.HasAggregation, aggAnalysis.Functions)

		// 查询复杂度分析
		complexity := sqlparser.AnalyzeQueryComplexity(stmt)
		fmt.Printf("  复杂度: %s (分数: %d)\n",
			complexity.ComplexityLevel, complexity.ComplexityScore)

		fmt.Println()
	}

	// SELECT列表中的子查询示例 - 完全支持
	fmt.Println("=== ✅ SELECT列表中的子查询示例（完全支持）===")
	selectSubqueries := []string{
		"SELECT name, (SELECT COUNT(*) FROM orders WHERE user_id = users.id) as order_count FROM users",
		"SELECT product_name, price, (SELECT AVG(price) FROM products) as avg_price FROM products",
		"SELECT category, (SELECT MAX(price) FROM products p WHERE p.category = products.category) as max_price FROM products",
	}

	for i, sql := range selectSubqueries {
		fmt.Printf("SELECT子查询示例 %d: %s\n", i+1, sql)
		
		stmt, err := parser.Parse(sql)
		if err != nil {
			log.Printf("解析错误: %v", err)
			continue
		}

		tables := sqlparser.ExtractAllTables(stmt)
		fmt.Printf("  涉及的表: %v\n", tables)

		tableAnalysis := sqlparser.AnalyzeTables(stmt)
		fmt.Printf("  表分析: 表数量=%d, 有连接=%v, 有子查询=%v\n",
			tableAnalysis.TableCount, tableAnalysis.HasJoins, tableAnalysis.HasSubquery)

		aggAnalysis := sqlparser.AnalyzeAggregation(stmt)
		fmt.Printf("  聚合分析: 包含聚合=%v, 聚合函数=%v\n",
			aggAnalysis.HasAggregation, aggAnalysis.Functions)

		complexity := sqlparser.AnalyzeQueryComplexity(stmt)
		fmt.Printf("  复杂度: %s (分数: %d)\n",
			complexity.ComplexityLevel, complexity.ComplexityScore)

		fmt.Println()
	}

	// FROM子查询示例 - 部分支持（有限制）
	fmt.Println("=== ⚠️ FROM子查询示例（部分支持，有解析限制）===")
	fromSubqueries := []string{
		"SELECT * FROM (SELECT * FROM users WHERE age > 18) AS adults",
		"SELECT avg_price.category FROM (SELECT category_id, AVG(price) as avg_price FROM products GROUP BY category_id) as avg_price",
		"SELECT top_users.name FROM (SELECT name FROM users ORDER BY created_at DESC LIMIT 10) as top_users",
	}

	for i, sql := range fromSubqueries {
		fmt.Printf("FROM子查询示例 %d: %s\n", i+1, sql)
		
		stmt, err := parser.Parse(sql)
		if err != nil {
			log.Printf("⚠️ 解析错误（预期的限制）: %v", err)
			continue
		}

		tables := sqlparser.ExtractAllTables(stmt)
		fmt.Printf("  涉及的表: %v\n", tables)

		tableAnalysis := sqlparser.AnalyzeTables(stmt)
		fmt.Printf("  表分析: 表数量=%d, 有连接=%v, 有子查询=%v\n",
			tableAnalysis.TableCount, tableAnalysis.HasJoins, tableAnalysis.HasSubquery)

		complexity := sqlparser.AnalyzeQueryComplexity(stmt)
		fmt.Printf("  复杂度: %s (分数: %d)\n",
			complexity.ComplexityLevel, complexity.ComplexityScore)

		fmt.Println()
	}

	fmt.Println("=== 📝 总结 ===")
	fmt.Println("✅ WHERE子查询和SELECT列表中的子查询完全支持")
	fmt.Println("⚠️ FROM子句中的子查询存在解析限制")
	fmt.Println("📊 所有成功解析的子查询都能正确进行表分析和聚合分析")
}